import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.Scanner;

public class Movies {
    private static LinkedList<Movies> movieList = new LinkedList<>();

    public static LinkedList<Movies> getMovieList() {
        return movieList;
    }

    public static void setMovieList(LinkedList<Movies> movieList) {
        Movies.movieList = movieList;
    }

    String movieName;    // 片名
    String director;     // 导演
    String[] actors;     // 主演
    String description;  // 剧情简介
    String movieLength;  // 时长
    double score;        // 评分

    public Movies() {
    }

    public Movies(String name, String director, String[] actors, String desc, String length, double score) {
        this.movieName = name;
        this.director = director;
        this.actors = actors;
        this.description = desc;
        this.movieLength = length;
        this.score = score;
    }

    // 查询影片
    public void searchMovie() {
        Scanner scanner = new Scanner(System.in);

        // 获取用户输入的查询条件（均为可选）
        System.out.println("请输入影片名称（可选，支持模糊查询）：");
        String name = scanner.nextLine().trim();

        System.out.println("请输入导演（可选，支持模糊查询）：");
        String director = scanner.nextLine().trim();

        System.out.println("请输入主演（可选，支持模糊查询）：");
        String actor = scanner.nextLine().trim();

        boolean found = false;
        System.out.println("\n========== 查询结果 ==========");

        for (Movies movie : movieList) {
            boolean matches = true;

            // 影片名称匹配（如果输入了名称条件）
            if (!name.isEmpty() && !movie.movieName.contains(name)) {
                matches = false;
            }

            // 导演匹配（如果输入了导演条件）
            if (matches && !director.isEmpty() && !movie.director.contains(director)) {
                matches = false;
            }

            // 主演匹配（如果输入了主演条件）
            if (matches && !actor.isEmpty()) {
                boolean actorMatch = false;
                for (String a : movie.actors) {
                    if (a.contains(actor)) {
                        actorMatch = true;
                        break;
                    }
                }
                if (!actorMatch) {
                    matches = false;
                }
            }

            // 如果所有条件都匹配，则显示影片信息
            if (matches) {
                System.out.println("片名：" + movie.movieName);
                System.out.println("导演：" + movie.director);
                System.out.println("主演：" + String.join(", ", movie.actors));
                System.out.println("时长：" + movie.movieLength);
                System.out.println("评分：" + movie.score);
                System.out.println("简介：" + movie.description);
                System.out.println("============================\n");
                found = true;
            }
        }

        if (!found) {
            System.out.println("未找到符合条件的影片！");
        }
    }

    // 添加影片
    public void addMovie() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入影片名称：");
        String name = scanner.nextLine();

        System.out.println("请输入导演：");
        String director = scanner.nextLine();

        System.out.println("请输入主演（多个主演用逗号分隔）：");
        String[] actors = scanner.nextLine().split(",");

        System.out.println("请输入影片时长(分钟，直接输入数字如124):");
        String length = scanner.nextLine();

        System.out.println("请输入影片评分：");
        double score = scanner.nextDouble();
        scanner.nextLine(); // 消耗换行符

        System.out.println("请输入剧情简介：");
        String desc = scanner.nextLine();

        movieList.add(new Movies(name, director, actors, desc, length, score));
        System.out.println("影片添加成功！");
    }

    // 列出所有影片
    public void listAllMovies() {
        System.out.println("\n========== 所有影片信息 ==========");
        for (Movies movie : movieList) {
            System.out.println("片名：" + movie.movieName);
            System.out.println("导演：" + movie.director);
            System.out.println("主演：" + String.join(", ", movie.actors));
            System.out.println("时长：" + movie.movieLength);
            System.out.println("评分：" + movie.score);
            System.out.println("简介：" + movie.description);
            System.out.println("============================\n");
        }
    }

    // 修改影片信息
    public void modifyMovie() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要修改的影片名称：");
        String name = scanner.nextLine();

        for (Movies movie : movieList) {
            if (movie.movieName.equals(name)) {
                System.out.println("请输入新导演（直接回车保持原值）：");
                String director = scanner.nextLine();
                if (!director.isEmpty()) movie.director = director;

                System.out.println("请输入新主演（多个主演用逗号分隔，直接回车保持原值）：");
                String actorsInput = scanner.nextLine();
                if (!actorsInput.isEmpty()) movie.actors = actorsInput.split(",");

                System.out.println("请输入新时长（直接回车保持原值）：");
                String length = scanner.nextLine();
                if (!length.isEmpty()) movie.movieLength = length;

                System.out.println("请输入新评分（0-10分，直接回车保持原值）：");
                String scoreStr = scanner.nextLine();
                if (!scoreStr.isEmpty()) movie.score = Double.parseDouble(scoreStr);

                System.out.println("请输入新剧情简介（直接回车保持原值）：");
                String desc = scanner.nextLine();
                if (!desc.isEmpty()) movie.description = desc;

                System.out.println("影片信息修改成功！");
                return;
            }
        }
        System.out.println("未找到该影片！");
    }

    // 删除影片
    public void deleteMovie() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要删除的影片名称：");
        String name = scanner.nextLine();

        // 检查是否存在该影片
        boolean movieExists = false;
        for (Movies movie : movieList) {
            if (movie.movieName.equals(name)) {
                movieExists = true;
                break;
            }
        }
        if (!movieExists) {
            System.out.println("未找到该影片！");
            return;
        }

        // 检查该影片是否有未来场次
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date now = new Date();
        boolean hasUpcomingSessions = false;

        for (Session session : Session.getSessionList()) {
            if (session.getMovieName().equals(name)) {
                try {
                    Date sessionDate = sdf.parse(session.getStartTime());
                    // 检查场次是否在当前时间之后
                    if (sessionDate.after(now)) {
                        hasUpcomingSessions = true;
                        break;
                    }
                } catch (ParseException e) {
                    System.out.println("场次时间格式错误: " + session.getStartTime());
                }
            }
        }

        // 如果有未来场次，阻止删除
        if (hasUpcomingSessions) {
            System.out.println("无法删除影片：\"" + name + "\"，该影片存在未来场次。");
            System.out.println("请先删除所有相关未来场次后再尝试删除影片。");
            return;
        }

        // 确认删除
        System.out.println("确定要删除影片 \"" + name + "\" 吗？(y/n)");
        if (!scanner.nextLine().equalsIgnoreCase("y")) {
            return;
        }

        // 删除影片
        movieList.removeIf(movie -> movie.movieName.equals(name));
        System.out.println("影片删除成功！");
    }


    public static Movies getMovieByName(String name) {
        for (Movies movie : movieList) {
            if (movie.movieName.equals(name)) {
                return movie;
            }
        }
        return null; // 如果没有找到返回null
    }

    public static int getMovieDuration(String movieName) {
        for (Movies movie : movieList) {
            if (movie.movieName.equals(movieName)) {
                try {
                    // 直接解析为整数分钟数
                    return Integer.parseInt(movie.movieLength.trim());
                } catch (NumberFormatException e) {
                    System.out.println("电影《" + movieName + "》时长格式错误：" + movie.movieLength);
                    return -1;
                }
            }
        }
        System.out.println("未找到电影《" + movieName + "》");
        return -1;
    }

    // 获取未来一周未排片的电影
    public static LinkedList<Movies> getUnscheduledMovies() {
        LinkedList<Movies> allMovies = getAllMovies();
        LinkedList<Movies> unscheduled = new LinkedList<>();

        // 获取未来一周的日期范围
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String today = sdf.format(new Date());
        String endDate = getDateAfterDays(today, 7);

        for (Movies movie : allMovies) {
            boolean hasScheduled = false;

            // 检查该电影是否已有排片
            for (Session session : Session.getSessionList()) {
                if (session.getMovieName().equals(movie.getName()) &&
                        session.getStartTime().compareTo(today) >= 0 &&
                        session.getStartTime().compareTo(endDate) < 0) {
                    hasScheduled = true;
                    break;
                }
            }

            if (!hasScheduled) {
                unscheduled.add(movie);
            }
        }

        return unscheduled;
    }

    public static String getDateAfterDays(String startDate, int days) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(sdf.parse(startDate));
            calendar.add(Calendar.DATE, days);
            return sdf.format(calendar.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
            return startDate; // Return original date if parsing fails
        }
    }

    public double getScore() {
        return score;
    }

    public int getDuration() {
        try {
            return Integer.parseInt(movieLength);
        } catch (NumberFormatException e) {
            return 120; // Default to 120 minutes if format is invalid
        }
    }

    public String getName() {
        return movieName;
    }

    public static LinkedList<Movies> getAllMovies() {
        return movieList;
    }


}

